/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package eu.anorien.dmo.gui.optimization;

import eu.anorien.dmo.Function;
import eu.anorien.dmo.Server;
import java.util.ArrayList;
import java.util.Random;
import org.apache.log4j.Logger;

/**
 *
 * @author David Miguel Antunes <davidmiguel [ at ] antunes.net>
 */
public class MonteCarloOptimization extends Optimization {

    private static final Logger logger = Logger.getLogger(MonteCarloOptimization.class);
    private MonteCarloOptimizationConfigPanel configPanel;

    public MonteCarloOptimization(Function function, ArrayList<Server> servers) {
        super(function, servers);
        this.function = function;
        configPanel = new MonteCarloOptimizationConfigPanel(this);
        tabbedPane.add(configPanel, 0);
        tabbedPane.setTitleAt(0, "Configuration");
        tabbedPane.setSelectedIndex(0);
    }

    public String toString() {
        return function.getName() + " Monte Carlo";
    }

    @Override
    public void stop() {
        configPanel.getStopButton().setEnabled(false);
        super.stop();
    }

    public void start() {
        configPanel.getStartButton().setEnabled(false);
        super.start();
        output.write("Starting optimization...");
        
        random = new Random(configPanel.getRandomSeed());
        stopAfter = configPanel.getStopAfter();

        for (int i = 0; i < configPanel.getNumThreads(); i++) {
            Thread t = new Thread() {

                public void run() {
                    while (!terminate) {
                        Object[] paramsArray = pointToParams(newRandomPoint());
                        try {
                            runFunction(paramsArray);
                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }
                    }
                }
            };
            threads.add(t);
            t.start();
        }
        configPanel.getStopButton().setEnabled(true);
    }
}
